import geopandas as gpd
from shapely.geometry import LineString,Point
import pandas as pd
import numpy as np
from scipy.spatial.distance import cdist
from math import atan2, degrees
from utils.simutils import calculate_metrics4_df
import time
import math

""" 计算相似性的匹配方法 """
start_time = time.time()

def anglesim(line1, line2):
    """ 输入为linestring """
    if line1.is_closed:
        angle1=0
    else:
        angle1 = degrees(atan2(line1.coords[-1][1] - line1.coords[0][1], line1.coords[-1][0] - line1.coords[0][0]))
        if angle1 < 0:
            angle1+=180
    if line2.is_closed:
        angle2=0
    else:
        angle2 = degrees(atan2(line2.coords[-1][1] - line2.coords[0][1], line2.coords[-1][0] - line2.coords[0][0]))
        if angle2 < 0:
            angle2+=180
    angle=abs(angle1-angle2)
    if angle > 90:
        angle = 180 - angle
    
    angle_radians = math.radians(angle)
    Sim = math.sin(angle_radians)

    return Sim

def lensim(line1, line2):
    lengtha = line1.length
    lengthb = line2.length
    
    if min(lengtha,lengthb)>0:
        similarity_score=min(lengtha,lengthb)/max(lengtha,lengthb)
    else:
         similarity_score=0

    return similarity_score

def compute_smhd(line1, line2):
    """ 输入为linestring """
    if line1.length <= line2.length:
        shorter, longer = line1, line2
    else:
        shorter, longer = line2, line1
    # 获取较短线段的顶点
    points = [Point(coords) for coords in shorter.coords]
    # 计算每个顶点到较长线段的距离
    distances = [longer.distance(p) for p in points]
    return np.median(distances)

def shapesim(line1, line2):
    buffer_distance = 25  # 使用25米缓冲区
    buffer_a = line1.buffer(buffer_distance)
    buffer_b = line2.buffer(buffer_distance)
    intersection = buffer_a.intersection(buffer_b)
    union = buffer_a.union(buffer_b)
    iou = intersection.area / max(buffer_a.area,buffer_b.area) if union.area > 0 else 0
    return iou 


def calculate_similarity(row, contour1, contour2):
    """综合相似度计算"""

    line1 = contour1[contour1['myid'] == row['col1']][['geometry']].reset_index(drop=True)
    line2 = contour2[contour2['myid'] == row['col2']][['geometry']].reset_index(drop=True)

    tolerance = 2
    simplified1 = line1.geometry.iloc[0].simplify(tolerance)
    simplified2 = line2.geometry.iloc[0].simplify(tolerance)

    # Simp1 = gpd.GeoSeries([simplified1], crs=line1.crs) 
    # Simp2 = gpd.GeoSeries([simplified2], crs=line1.crs) 
    fd=(anglesim(simplified1,simplified2)+lensim(simplified1,simplified2)+shapesim(simplified1,simplified2))/3
    
    # print(fd)
    MR=0
    if fd>0.6:
        MR=1

    return fd,MR

""" 需修改3个参数 """
# 读入数据
# #加利福尼亚
contour1 = gpd.read_file('E:/Data/QGIS/2contour/Calif/ClfUg_Ct.shp' ,encoding='gbk')
contour2= gpd.read_file('E:/Data/QGIS/2contour/Calif/ClfDem_Ct.shp' ,encoding='gbk')
# # 香港
# contour1 = gpd.read_file('E:/Data/QGIS/2contour/HG/HG2W_CtG.shp' ,encoding='gbk')
# contour2= gpd.read_file('E:/Data/QGIS/2contour/HG/HGDEM_CtG.shp' ,encoding='gbk')
match_df0 = pd.read_csv('dataCPR/HG_FMR0.csv')


# 遍历匹配关系并计算相似度
for idx, row in match_df0.iterrows():
    print(idx)
    sim, MR = calculate_similarity(row, contour1, contour2)
    match_df0.at[idx, 'sim'] = sim
    match_df0.at[idx, 'pre'] = MR


# 保存结果到CSV文件
match_df0.to_csv('dataCPR/HGSim0.csv', index=False)
#计算精度
pred = match_df0['pre'].values
y = match_df0['Ture'].values
acc1,precision1, recall1, f11= calculate_metrics4_df(pred, y)
print('parameter1: {:.4f} {:.4f} {:.4f}'.format(precision1, recall1, f11))

print(f"总执行时间: {time.time()-start_time:.2f}秒")